package com.winshare.saleAssistant.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.winshare.saleAssistant.domain.dto.req.UserQueryDTO;
import com.winshare.saleAssistant.domain.entity.ProductInfoDO;
import com.winshare.saleAssistant.excelUtil.ExcelUtils;
import com.winshare.saleAssistant.model.*;
import com.winshare.saleAssistant.modelVo.SaleExcel;
import com.winshare.saleAssistant.service.*;
import com.winshare.saleAssistant.util.LogicResponse;
import com.winshare.saleAssistant.util.PageFactory;
import com.winshare.saleAssistant.util.ToolUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 控制器
 *
 * @author fengshuonan
 * @Date 2020-11-11 10:51:38
 */
@Controller
@RequestMapping("/sys/sale")
public class SaleController {


    @Autowired
    private ISaleService saleService;

    @Autowired
    private ISaleImportLogService saleImportLogService;

    @Autowired
    private ISchoolService schoolService;

    @Autowired
    private ISchoolHardwareService schoolHardwareService;

    @Autowired
    private ISaleSynchronousService saleSynchronousService;

    @Autowired
    private ProductInfoService productInfoService;


    /**
     * 最后更新时间
     */
    @RequestMapping("/synchronousTime")
    @ResponseBody
    public Object getSynchronousTime() {
        return LogicResponse.success(saleImportLogService.getSynchronousTime());
    }

    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestBody UserQueryDTO userQueryDTO) {
        return LogicResponse.success(saleService.selectSaleByCondition(userQueryDTO));
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Sale sale) {
        saleService.save(sale);
        return LogicResponse.success("success");
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer saleId) {
        saleService.removeById(saleId);
        return LogicResponse.success("success");
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Sale sale) {
        saleService.updateById(sale);
        return LogicResponse.success("success");
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{saleId}")
    @ResponseBody
    public Object detail(@PathVariable("saleId") Integer saleId) {
        return saleService.getById(saleId);
    }

    /**
     * 导入
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ResponseBody
    public Object importData(@RequestParam(value = "mFile") MultipartFile myfile, String uuid) {
        if (ToolUtil.isNotEmpty(uuid)) {
            saleService.deleteByUuid(uuid);
        }
        return importExcel(myfile);
    }

    public Object importExcel(MultipartFile myfile) {
        List<SaleExcel> saleExcels = ExcelUtils.readExcel(null, SaleExcel.class, myfile);
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        System.out.println(myfile + "===============");
        List<Sale> list = new ArrayList<>();
        for (SaleExcel saleExcel : saleExcels) {
            System.out.println(saleExcel.getCreateTime() + "导入时间");
            Sale sale = new Sale();
            //把saleExcel实体类 复制到 数据库实体类中
            BeanUtils.copyProperties(saleExcel, sale);
            list.add(sale);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < saleExcels.size(); i++) {
            System.out.println(saleExcels.size() + "saleExcels的长度");
            SaleExcel saleExcel1 = saleExcels.get(i);
            for (int j = 0; j < list.size(); j++) {
                if (saleExcel1.getSchoolCode().equals(list.get(j).getSchoolCode()) && saleExcel1.getProductCode().equals(list.get(j).getProductCode())
                        && saleExcel1.getVersionCode().equals(list.get(j).getVersionCode()) && saleExcel1.getSaleNumber().equals(list.get(j).getSaleNumber())
                        && saleExcel1.getSalesPrice().equals(list.get(j).getSalesPrice()) && saleExcel1.getPurchasePrice().equals(list.get(j).getPurchasePrice())) {
                    list.get(j).setSaleUuid(s);
                    try {
                        String createTime = saleExcel1.getCreateTime();
                        String replace = createTime.replace("/", "-");
                        Date parse = df.parse(replace);
                        list.get(j).setCreateTime(parse);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        //根据学校school_code 查出学校id 保存到list 中
        List<SchoolHardware> schools = schoolHardwareService.list(null);
        //根据产品编号 查出产品id 保存到list 中
        List<ProductInfoDO> products = productInfoService.getProducts(null);
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Sale sale = list.get(i);
                if (!schools.isEmpty()) {
                    for (int j = 0; j < schools.size(); j++) {
                        SchoolHardware school = schools.get(j);
                        if (sale.getSchoolCode().equals(school.getSapCode())) {
                            sale.setSchoolId(school.getId());
                        }
                    }
                    if (!products.isEmpty()) {
                        for (int o = 0; o < products.size(); o++) {
                            ProductInfoDO product = products.get(o);
                            if (sale.getProductCode().equals(product.getProductCode())) {
                                sale.setProductId(Integer.parseInt(product.getId().toString()));
                            }
                        }
                    }
                }
            }
        }
        saleService.saveBatch(list);
        //文件上传
        if (myfile.isEmpty()) {
            return "文件为空";
        }
        // 获取文件名
        String fileName = myfile.getOriginalFilename();
        System.out.println("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为：" + suffixName);
        try {
            String fileUploadPath = getFileUploadPath();
            System.out.println(fileUploadPath + "路径------");
            //  picture.transferTo(new File(fileSavePath + pictureName));
            myfile.transferTo(new File(fileUploadPath + fileName));
            SaleImportLog saleImportLog = new SaleImportLog();
            saleImportLog.setFileName(fileName);
            Date time = new Date();
            saleImportLog.setImportTime(time);
            saleImportLog.setAddrFile(fileUploadPath);
            saleImportLog.setUuid(s);
            saleImportLogService.save(saleImportLog);
            //记录时间存到更新时间表
            SaleSynchronous saleSynchronous = new SaleSynchronous();
            saleSynchronous.setCreatTime(time);
            saleSynchronousService.save(saleSynchronous);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return LogicResponse.success("success");
    }

    /**
     * 文件下载
     *
     * @param id
     * @param response
     */
    @RequestMapping("/downloadFile")
    public void download(String id, HttpServletResponse response) {
        //获取该文件的名称、后缀
        SaleImportLog saleImportLog = saleImportLogService.getById(id);
        //文件在服务器的路径
        String path = saleImportLog.getAddrFile() + saleImportLog.getFileName();
        InputStream inputStream = null;
        OutputStream out = null;
        try {
            FileInputStream fileInputStream = new FileInputStream(path);
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            String fileName = saleImportLog.getFileName();      //abcd.png
            //设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            //设置文件头：最后一个参数是设置下载文件名（设置编码格式防止下载的文件名乱码）
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
            out = response.getOutputStream();
            int b = 0;
            while (b != -1) {
                b = fileInputStream.read(buffer);
                //写到输出流(out)中
                out.write(buffer, 0, b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                out.close();
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private String fileUploadPath;
    private Boolean haveCreatePath = false;

    public String getFileUploadPath() {
        //如果没有写文件上传路径,保存到临时目录
        if (ToolUtil.isEmpty(fileUploadPath)) {
            return ToolUtil.getTempPath();
        } else {
            //判断有没有结尾符,没有得加上
            if (!fileUploadPath.endsWith(File.separator)) {
                fileUploadPath = fileUploadPath + File.separator;
            }
            //判断目录存不存在,不存在得加上
            if (!haveCreatePath) {
                File file = new File(fileUploadPath);
                file.mkdirs();
                haveCreatePath = true;
            }
            return fileUploadPath;
        }
    }
}
